/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2022-12-12 16:46:22
 * @LastEditors: huangtianyang
 * @LastEditTime: 2023-08-31 15:14:47
 * @FilePath: \cxl-admin\src\pages\company\h5User\edit\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { checkPassword, regMobile } from '@/utils'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { selectCompany } from '@/apis/company/audit'
import { accountInterface, h5AccountAdd, h5AccountUpdate } from '@/apis/company/h5'
import { userStore } from '@/store/user.store'

/**
 * 定义基本信息接口
 */
interface InformationInterface {
    company?: string
    companyId?: string
    name: string
    phone: string
    password?: string
    status: boolean
    type?: string
    userId?: string
}

/**
 * 定义页面跳转传递的参数类型，移除password
 */
export type queryType = Omit<InformationInterface, 'password'>

export class H5UserData {
    //基本信息
    information = reactive({
        company: '',
        companyId: '',
        userId: '',
        name: '',
        phone: '',
        password: '',
        status: '',
        type: ''
    })
    //校验规则
    rules = reactive({
        name: { required: true, message: '请输入姓名', trigger: 'blur' },
        phone: { required: true, validator: this.phoneValidatePass, trigger: 'blur' },
        password: { required: true, validator: this.passwordValidatePass.bind(this), trigger: 'blur' }
    })
    //用户仓库
    uStore = userStore()
    //类型 edit | add
    type: string | undefined
    // 编辑对象id
    id: string | undefined
    //选中权限菜单的id
    checkedId: any[] = reactive([])
    //默认的密码8个空格
    defaultPassword = '        '
    loading = ref(false)
    //定义公司选择器
    companyOptions: any[] = reactive([])

    constructor() {}

    //重置数据
    resetData = () => {
        this.information.company = ''
        this.information.companyId = ''
        this.information.userId = ''
        this.information.name = ''
        this.information.phone = ''
        this.information.password = ''
        this.information.status = ''
        this.information.type = ''
    }

    /**
     * 验证输入的是否是正确的手机号
     * @param rule
     * @param value
     * @param callback
     */
    phoneValidatePass(rule: any, value: any, callback: any) {
        if (value === '') {
            callback(new Error('请输入手机号码'))
        } else {
            regMobile(value) ? callback() : callback(new Error('手机号有误，请重新输入'))
        }
    }
    /**
     * 验证输入的是否是正确的密码
     * @param rule
     * @param value
     * @param callback
     */
    passwordValidatePass(rule: any, value: any, callback: any) {
        console.log('value', value)
        if (value === '') {
            callback(new Error('请输入密码'))
        } else if (value == this.defaultPassword) {
            console.log(value, this.defaultPassword)
            // callback(new Error('请输入密码'))
            callback()
        } else {
            console.log(value)
            checkPassword(value) ? callback() : callback(new Error('密码格式不符合（英文+数字至少8位），请重新输入'))
        }
    }
    /**
     * 监听用户输入的公司名，搜索
     * @param query
     */
    remoteMethod = (query: string) => {
        if (query) {
            this.loading.value = true
            this.getCompanyList(query, () => {
                this.loading.value = false
            })
        }
    }

    /**
     * 监听选择的公司
     * @param res
     */
    onSelectCompany = (res: any) => {
        console.log(res)
        this.information.companyId = res
    }
    /**
     * 获取公司
     * @param name
     * @param callback
     */
    getCompanyList(name = '', callback = () => {}) {
        selectCompany({ current: 1, size: 10, companyParam: name }).then(res => {
            if (res.data.value === 200) {
                this.companyOptions.length = 0
                res.data.data.records.map((item: any) => {
                    this.companyOptions.push({ value: item.companyId, label: `${item.companyName}` })
                })
                // this.tableData.length = 0
                // this.tableData.push(...res.data.data.records)
                // this.pagination.total = res.data.data.total
                callback()
            }
        })
    }
    //点击确定按钮
    comfirm = (callback = () => {}) => {
        if (this.information.type === 'create') {
            h5AccountAdd({
                companyId: this.information.companyId,
                userName: this.information.name,
                userPassword: this.information.password,
                userPhone: this.information.phone
            }).then(res => {
                if (res.data.value === 200) {
                    ElMessage.success('新增成功！')
                    callback()
                } else {
                    ElMessage.error(res.data.desc)
                }
            })
        } else if (this.information.type === 'edit') {
            console.log('this.information.password', this.information.password)
            const p: accountInterface = {
                companyId: this.information.companyId,
                userName: this.information.name,
                userPhone: this.information.phone,
                userPassword: this.information.password.trim() ? this.information.password : null
            }
            h5AccountUpdate(this.information.userId, p).then(res => {
                if (res.data.value === 200) {
                    ElMessage.success('修改成功！')
                    callback()
                } else {
                    ElMessage.error(res.data.desc)
                }
            })
        }
    }
    //监听是否改变了密码
    frist = false
    editPassword = (res: any) => {
        console.log(res.length)
        if (this.frist) {
            this.frist = res.length === 8 ? true : false
        }
    }
    focusPassword = () => {
        console.log('focus')
        this.information.password = ''
        this.frist = true
    }
    blurPassword = () => {
        console.log('blur')
        if (this.information.password.length === 0) {
            //this.information.password = this.defaultPassword
        }
    }
}
